import lang from './i18n.js'
import { MenuBgParams } from '@swda/configs/params/MenuBg'
import Window_SWDA_File from './fileWindow.js'

const createBackgroundByBitmapUrl = (target, bitmapUrl) => {
    if (!bitmapUrl) return;

    target._backgroundSprite = new Sprite();
    const bitmap = ImageManager.loadBitmap('img/system/UI/', bitmapUrl);
    target._backgroundSprite.bitmap = bitmap
    target.addChild(target._backgroundSprite);
}

/**
 * 保存场景和读取场景的基类
 */
class SWDA_Scene_Record_Base extends Scene_MenuBase {
    constructor() {
        super(...arguments)
    }

    initialize() {
        const width = Graphics.boxWidth + 48
        const height = Graphics.boxHeight + 48
        super.initialize(-24, -24, width, height)
    }
    /*
    start() {
        Scene_MenuBase.prototype.start.call(this);
        if(SceneManager._previousClass == Scene_Title)
            this.startFadeIn(this.fadeSpeed());
    }
    */
    mode() {
        return 'save';
    }

    title() {
        const map = {
            save: lang.save,
            load: lang.load,
        }
        return map[this.mode()]
    }

    savefileId() {
        return this._mainWindow.index()
    }

    create() {
        super.create()
        this.createMainWindow()
        this.createConfirmWindow()
    }

    createBackground() {
        this._backgroundSprite = new Sprite();
        if(SceneManager._previousClass == Scene_Title || SceneManager._previousClass == Scene_Gameover){
            this._backgroundSprite.bitmap = ImageManager.loadTitle1('Title0');
        }else{
            this._backgroundSprite.bitmap = SceneManager.backgroundBitmap();
        }
        this.addChild(this._backgroundSprite);
        createBackgroundByBitmapUrl(this, MenuBgParams.bgBitmapRecord)
    }

    createMainWindow() {
        this._mainWindow = new Window_SWDA_File({
            mode: this.mode(),
            title: this.title()
        })
        this._mainWindow.select(this.firstSavefileIndex());
        this._mainWindow.setHandler('ok', this.onSavefileOk.bind(this))
        this._mainWindow.setHandler('cancel', this.onBeforeLeaveWindow.bind(this))
        this._mainWindow.refresh();
        this.addWindow(this._mainWindow)
    }

    createConfirmWindow () {
    };
    
    createDialogWindow() {
    }


    onBeforeLeaveWindow() {
        DataManager.clearSnapShotCache()
        if(SceneManager._previousClass == Scene_Gameover)
            SceneManager.goto(Scene_Title);
        else
            this.popScene()
    }

    onSavefileOk() {
    }

}


/**
 * 保存场景类
 */
export class Scene_Save extends SWDA_Scene_Record_Base {
    constructor() {
        super(...arguments)
    }
    mode() {
        return 'save'
    }

    onSavefileOk() {
        if(this._mainWindow.hasSaveFile(this._mainWindow.index())){
            this._mainWindow.drawConfirm();
            this._mainWindow.deactivate();
            this._confirmWindow.activate();
            this._confirmWindow.show();
        }else{
            this.onConfirmOk();
        }
        

    }

    onConfirmOk() {
        this._mainWindow.clearConfirm()
        super.onSavefileOk()
        $gameSystem.onBeforeSave();
        if (DataManager.saveGame(this.savefileId())) {
            this.onSaveSuccess();
        } else {
            this.onSaveFailure();
        }
    }

    onConfirmCancel() {
        this._mainWindow.clearConfirm()
        this._mainWindow.activate();
        this._confirmWindow.deactivate();
        this._confirmWindow.hide();
    }
    onSaveSuccess() {
        SoundManager.playSave();
        DataManager.clearSnapShotCache()
        StorageManager.cleanBackup(this.savefileId());
        this.popScene();
    }

    onSaveFailure() {
        SoundManager.playBuzzer();
        this.activateListWindow();
    }

    firstSavefileIndex() {
        return DataManager.lastAccessedSavefileId();
    };

    createConfirmWindow () {
        this._confirmWindow = new Window_FileCoverConfirm();
        this._confirmWindow.setHandler('ok',  this.onConfirmOk.bind(this));
        this._confirmWindow.setHandler('cancel',   this.onConfirmCancel.bind(this));
        this._confirmWindow.hide();
        this._confirmWindow.deactivate();
        this.addWindow(this._confirmWindow);
    };

}

/**
 * 读取场景类
 */
export class Scene_Load extends SWDA_Scene_Record_Base {
    constructor() {
        super(...arguments)
    }

    mode() {
        return 'load'
    }

    savefileId() {
        return this._mainWindow.index();
    }

    terminate() {
        super.terminate()
        if (this._loadSuccess) {
            $gameSystem.onAfterLoad();
        }
    }

    onSavefileOk() {
        super.onSavefileOk()
        if (DataManager.loadGame(this.savefileId())) {
            this.onLoadSuccess();
        } else {
            this.onLoadFailure();
        }
    }

    onLoadSuccess() {
        SoundManager.playLoad();
        this.fadeOutAll();
        this.reloadMapIfUpdated();
        SceneManager.goto(Scene_Map);
        this._loadSuccess = true;
        SceneManager._isTitleOptions = false;
    }

    onLoadFailure() {
        SoundManager.playBuzzer();
        this._mainWindow.activate();
    }

    reloadMapIfUpdated() {
        if ($gameSystem.versionId() !== $dataSystem.versionId) {
            $gamePlayer.reserveTransfer($gameMap.mapId(), $gamePlayer.x, $gamePlayer.y);
            $gamePlayer.requestMapReload();
        }
    }

    firstSavefileIndex() {
        return DataManager.latestSavefileId();
    };
}
